let xss = require('xss');
let socket_chat = (server) => {
    let io = require('socket.io')(server);
    io.on('connection', function (socket) {
        socket.on('register', function (data) {
            data.username = xss(data.username, {
                whiteList: [],
                stripIgnoreTag: true,
                stripIgnoreTagBody: ['script']
            });
            data.password = xss(data.password, {
                whiteList: [],
                stripIgnoreTag: true,
                stripIgnoreTagBody: ['script']
            })
        })
        socket.on('broadcast', function (data) {
            console.log(data);
            data.info = xss(data.info, {
                whiteList: [],
                stripIgnoreTag: true,
                stripIgnoreTagBody: ['script']
            });
            let time = new Date();
            data.timestamp = time.getTime();
            console.log(data);
            if (data.info !== '') {//过滤xss，不转发
                let cookie_info = data.cookie_info.match(/username.*/);
                if (cookie_info) {
                    cookie_info = cookie_info[0].split('=');
                    let username = cookie_info[1];
                    socket.broadcast.emit('res_broadcast', {
                        res: data.info,
                        username: username,
                        time: data.timestamp
                    });
                    socket.emit('confirm_broadcast', {
                        res: 'success',
                        username: username,
                        info: data.info,
                        time: data.timestamp
                    });
                } else {
                    socket.emit('confirm_broadcast', {
                        res: 'err',
                        message: 'cookie已过期，请刷新重新登录'
                    });
                }
            }           
        });
    });
}

module.exports = socket_chat;